<template>
  <div class="app-container app-containerMoney containerMoneynews app-containerMoneytabel">
    <div class="filter-container">
      <el-select style="marginRight:15px;" size="small" v-model="listQuery.typeKey" placeholder="类型">
        <el-option v-for="item in defTypeOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-input size="small" placeholder="请输入标题" style="width: 200px;" class="filter-item"
          v-model="listQuery.searchStr"></el-input>
      <el-button size="small" class="filter-item filter-itemBut" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button size="small" class="filter-item filter-itemBut" type="primary" icon="el-icon-search" @click="handleCreate">添加</el-button>
    </div>
    <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column type="index" align="center" width="80" label="序号"></el-table-column>
      <el-table-column label="标题" align="center">
        <template slot-scope="scope">
          {{scope.row.title}}
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" width="150">
        <template slot-scope="scope">
          {{scope.row.type | mapLabel('newsType')}}
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span v-if="scope.row.createTime">{{scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handleDetails(scope.row)">详情</el-button>
          <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
        :page-sizes="[10,20,30, 50]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <!--新增修改弹出层-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form size="small" :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="80px" style='width: calc(100% - 100px); margin-left:50px;; margin-right:50px;'>
        <el-form-item label="地区" prop="areaCode" class="dialog-areaCode_User">
          <region-selector :province="region.province" :city="region.city" :area="region.area" 
            :street="region.street" :community="region.community"
            :area-code="temp.areaCode" @region="setAreaCode" ></region-selector>
        </el-form-item>
        <el-form-item label="类型" prop="type" v-if="dialogStatus=='create'">
          <el-select style="marginRight:15px;" size="small" v-model="temp.type" placeholder="类型">
            <el-option v-for="item in defTypeOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="temp.title"></el-input>
        </el-form-item>
        <el-form-item label="banner" prop="banner">
          <el-upload
            :action="uploadURL"
            list-type="picture-card"
            :limit="1"
            multiple
            :file-list="bannerFileList"
            :on-exceed="handleBannerExceed"
            :on-success="bannerUploadSuccess"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="附件" prop="files">
          <el-upload
            :action="uploadURL"
            :on-remove="handleRemove"
            :on-success="fileUploadSuccess"
            multiple
            :limit="5"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <div class="dataForm_tinymce">
            <tinymce :height="height" v-model="temp.content" id='tinymce'></tinymce>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">提交</el-button>
        <el-button v-else type="primary" @click="updateData">更新</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { queryPage, create, update, deleteById, queryInfo } from "@/api/news";
import Tinymce from "@/components/Tinymce";
import RegionSelector from "@/components/RegionSelector";
import { packRegionCode } from "@/utils/region";

export default {
  components: {
    Tinymce,
    RegionSelector
  },
  data() {
    return {
      height: 500,
      content: "",
      list: null,
      total: 0,
      listLoading: true,
      username: "",
      listQuery: {
        page: 1,
        size: 10,
        searchStr: null,
        type: null,
        sort: "+id"
      },
      defTypeOptions: this.$store.state.dict.options["newsType"],
      baseURL: process.env.BASE_API,
      uploadURL: process.env.BASE_API + "/file/upload",
      dialogFormVisible: false,
      dialogStatus: "",
      dialogImageUrl: "",
      dialogVisible: false,
      textMap: {
        update: "更新",
        create: "添加"
      },
      bannerFileList: [],
      fileList: [],
      enabledMap: {
        true: "启用",
        false: "禁用"
      },
      temp: {
        id: null,
        type: null,
        title: null,
        banner: null,
        content: null,
        files: []
      },
      region: {
        province: 0,
        city: 0,
        area: 0,
        street: 0,
        community: 0
      },
      rules: {}
    };
  },
  mounted: function() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.listLoading = true;
      queryPage(this.listQuery).then(response => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.listLoading = false;
      });
      this.listLoading = false;
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.fetchData();
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.fetchData();
    },
    handleCreate() {
      this.resetTemp();
      this.bannerFileList = [];
      this.fileList = [];
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    setAreaCode(value) {
      if (value.code) {
        this.temp.areaCode = value.code;
      }
    },
    handleDetails(row) {
      this.$router.push({
        name: "newdetails",
        query: { action: "view", id: row.id, time: row.createTime }
      });
      // closeCollectTag(this);
    },
    handleUpdate(row) {
      this.bannerFileList = [];
      this.fileList = [];
      queryInfo(row.id).then(res => {
        this.temp = res.data;
        this.dialogStatus = "update";
        this.dialogFormVisible = true;
        let tempBannerFile = {
          fileId: this.temp.banner,
          url: this.baseURL + "/file/" + this.temp.banner
        };
        this.bannerFileList.push(tempBannerFile);
        res.data.files.forEach(element => {
          let tempFile = {
            fileId: element.fileId,
            name: element.fileName,
            url: this.baseURL + "/file/" + element.fileId
          };
          this.fileList.push(tempFile);
        });
        //地区处理
        let areaCode = res.data.areaCode;
        if (areaCode && areaCode.length > 5) {
          this.region = packRegionCode(areaCode);
        }
      });
    },
    handleDelete(row) {
      const loading = this.$loading({
        lock: true,
        text: "提交中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      setTimeout(() => {
        loading.close();
      }, 800);
      this.$confirm("删除后不可恢复, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteById(row.id).then(() => {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
            const index = this.list.indexOf(row);
            this.list.splice(index, 1);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    bannerUploadSuccess(response, file, fileList) {
      this.temp.banner = response.data.fileId;
    },
    fileUploadSuccess(response, file, fileList) {
      let tempFile = {
        fileName: file.name,
        newsId: this.temp.id,
        fileId: response.data.fileId
      };
      this.temp.files.push(tempFile);
    },
    resetTemp() {
      this.temp = {
        id: null,
        type: null,
        title: null,
        banner: null,
        content: null,
        files: []
      };
      this.region = {
        province: 0,
        city: 0,
        area: 0,
        street: 0,
        community: 0
      };
    },
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          create(this.temp).then(() => {
            this.fetchData();
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp);
          update(tempData).then(() => {
            this.fetchData();
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    handleRemove() {},
    beforeRemove() {},
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 5 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    handleBannerExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    }
  }
};
</script>

<style scoped>
.dataForm_tinymce {
  height: 510px;
  width: 100%;
  overflow: hidden;
  padding: 3px;
}

.filter-container {
  margin-bottom: 20px;
  overflow: hidden;
}

.filter-container-option {
  display: flex;
  flex-wrap: nowrap;
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 25px;
  overflow: hidden;
  display: flex;
  justify-content: flex-end;
}

.app-containerMoney {
  margin-right: 20px;
}

.filter-itemBut {
  margin-left: 25px;
}
</style>